package com.order.controller;

import com.order.common.PageQuery;
import com.order.common.Result;
import com.order.entity.SysUser;
import com.order.service.UserService;
import com.order.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取技术员列表
     */
    @GetMapping("/tech-list")
    public Result<List<SysUser>> getTechList() {
        try {
            List<SysUser> techList = userService.getTechList();
            return Result.success(techList);
        } catch (Exception e) {
            return Result.error("获取技术员列表失败");
        }
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getUserStats(@RequestHeader("Authorization") String token) {
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            Map<String, Object> stats = userService.getUserStats(userId, roleType);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public Result<String> updateUserInfo(
            @RequestBody SysUser user,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            user.setId(userId);
            
            userService.updateUserInfo(user);
            return Result.success("更新成功");
        } catch (Exception e) {
            return Result.error("更新失败");
        }
    }

    /**
     * 分页查询用户列表（管理员功能）
     */
    @GetMapping("/list")
    public Result<List<SysUser>> getUserList(
            PageQuery pageQuery,
            @RequestParam(required = false) Integer roleType,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Integer currentUserRoleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有管理员可以查看用户列表
            if (currentUserRoleType != 1) {
                return Result.forbidden("无权限访问");
            }
            
            List<SysUser> users = userService.getUserList(
                pageQuery.getOffset(), pageQuery.getPageSize(), 
                pageQuery.getKeyword(), roleType);
            Long total = userService.countUsers(pageQuery.getKeyword(), roleType);
            
            return Result.success(users, total);
        } catch (Exception e) {
            return Result.error("查询用户列表失败");
        }
    }

    /**
     * 更新用户状态（管理员功能）
     */
    @PutMapping("/{id}/status")
    public Result<String> updateUserStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> request,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Integer currentUserRoleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有管理员可以更新用户状态
            if (currentUserRoleType != 1) {
                return Result.forbidden("无权限操作");
            }
            
            Integer status = request.get("status");
            userService.updateUserStatus(id, status);
            
            return Result.success("状态更新成功");
        } catch (Exception e) {
            return Result.error("状态更新失败");
        }
    }

    /**
     * 获取个人资料
     */
    @GetMapping("/profile")
    public Result<SysUser> getProfile(@RequestHeader("Authorization") String token) {
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            SysUser user = userService.getUserById(userId);
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("获取个人资料失败");
        }
    }

    /**
     * 更新个人资料
     */
    @PutMapping("/profile")
    public Result<String> updateProfile(
            @RequestBody SysUser user,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            user.setId(userId);
            
            userService.updateUserInfo(user);
            return Result.success("资料更新成功");
        } catch (Exception e) {
            return Result.error("资料更新失败");
        }
    }
}